
---
title: "R code: Upregulation of IFN-stimulated genes persists beyond the transitory transcriptomic storm of acute HIV-1 infection: data and statistical analyses."
author: "Romel D. Mackelprang, Mark J. Cameron, Abdelali Filali-Mouhim, Brian Richardson, Francois Lefebreve, Elly Katabira, Allan Ronald, Glenda Gray, Kristen Cohen, Nichole R. Klatt, Tiffany Pecor, Connie Celum, M Juliana McElrath, Sean M. Hughes, Florian Hladik, Jairam R. Lingappa, for the Partners in Prevention HSV/HIV Transmission Study and the Partners PrEP Study Teams"
output:
  html_document:
    message: false
    number_sections: true
    warnings: false	
    theme: cerulean
    toc: true



---

# Notes

* The R code here re-creates the analyses from the paper, the results
  reported in the text, the Figures and Supplementary Figures. The
  Supplementary table code is in a separate RMarkdown file:
  SupplementaryTables.R.
* Working directory: must be set to directory where this .Rmd file
  resides. This will ensure proper handling of R scripts, accessing
  data files and saving figures.
* This file runs all of the scripts that analyze the data and generate
  the statistics and figures for the paper.
* Each code chunk can be run independently except for the four
 subfigures of Figure 4, which depend on the code chunk Figure4. The
 reason for splitting them is because Rmarkdown has trouble plotting a
 gTable object that contains another gTable for the heatmap.
* The code for creating the base figures is shown here. However, the
  figures shown in the published paper were edited for formatting.


# Analysis code

The primary analyes are performed using the following scripts. Results
are saved in the ./DataIntermediate/ folder and loaded for reporting
the results below. Some of these Scripts take along time to
run. Therefore, they are not evaluated here.


```{r CreateExpressionChangesDataframe, eval=FALSE, message=FALSE}
### Create dataframe with gene expression changes relative to pre-infection
source('./RScripts/Analysis_CreateExpressionChangesDataframe.R')
### Create linear mixed models to determine gene expression trajectories.
source('./RScripts/Analysis_CreateTrajectories.R')
### GSEA
source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/Analysis_GseaFisher.R')
### Trajectoryies for cytokines
source('./RScripts/Analysis_LmmModels_Cytokines.R')
### Gene expression associations with cytokines and clinical HIV-1 outcomes.
source("./RScripts/Analysis_IsgAssociationsWithAnalytes.R")
### Determine whether ISGs in each trajectory are more or less likely to associated with analytes.
source('./RScripts/Analysis_IsgAnalyteAssociationTable.R')

```

# Results

The sections below correspond to the sections in the paper. Within
each section, code to obtain all statistics and figures in that
section is provided.

## Study participants and longitudinal HIV-1 characteristics

```{r ExpressionData, collapse=TRUE}

library(Biobase)

###Load expresssion set
load("./DataOriginal/SetPaper.Rdata")

cat("Number of participants: ", length(unique(Set$ptid)), '\n')
cat("Number of samples: ", nrow(pData(Set)), '\n')

require(knitr)
kable(table(Set$group), caption='Number of pre and post-infection samples.')

kable(table(Set$feibig), caption='Number of samples by HIV-1 stage.')

kable(as.matrix(summary(Set$days.after.inf[Set$group=='Post.infection'])),
                caption='Summary statistics for the number of days after HIV-1 infection that paxgene tubes were collected.')

kable(as.matrix(summary(tapply(rownames(pData(Set))[Set$group=='Post.infection'],
                               Set$ptid[Set$group=='Post.infection'], function(x){length(unique(x))}))),
      caption='Summary statistics for number of post-infection samples per participant')

kable(table(Set$gender[!duplicated(Set$ptid)]), caption='Biological sex of participants')
kable(table(Set$country[!duplicated(Set$ptid)]), caption='Country where participants were enrolled.')


```


```{r FigureS1, message=FALSE, collapse=TRUE, fig.cap="Figure S1: Collection of samples used in transcriptomics studies by participant and HIV-1 status at study visit."}

source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/FigureS1_SampleCollectionByTime.R')
p


```

## Human gene expression trajectories following HIV-1 infection

```{r SummaryTrajectories, message=FALSE, collapse=TRUE}
load('./DataIntermediate/pvs.Rdata')

require(knitr)
kable(table(pvs$fdr.p.cut), caption='FDR q-values greater or less than 0.05.')

kable(table(pvs$fdr.p.cut, 1.5<pvs$abs.change.fc), caption='FDR q-value greater or less than 0.05 by max. fold-change after infection greater or less than 1.5.')

kable(table(pvs$fdr.p.cut, pvs$abs.change.fc.cut), caption='FDR q-values by maximum absolute expression fold-change after HIV-1 infection. Q-value categories are shown in rows. Fold-change categories are shown in columns.')

kable(table(pvs$change.cat), caption='Longitudinal expression trajectories')

kable(pvs[pvs$change.cat=='continuous.increase',
          c('SYMBOL', 'p', 'fdr.p','abs.change.fc')],
      row.names=FALSE, caption='Genes in persistently up-regulated trajectory.')

load('./DataIntermediate/preds.Rdata')
kable(2^preds[pvs$nuID[pvs$SYMBOL=='IFI27'], '90'], caption='Estimated fold-change for IFI27 at 90 days after infection.')

DT::datatable(pvs[pvs$change.cat=='peak.increase',
                  c('SYMBOL', 'p', 'fdr.p','abs.change.fc')],
              rownames=FALSE, caption='Genes in the transiently up-regulated trajectory.')

```

```{r Figure1, message=FALSE, collapse=TRUE, width=8, height=4, fig.cap="Figure 1. Post HIV-1 infection gene expression trajectories relative to pre-infection expression levels. Analysis is based on linear mixed models with time since HIV-1 infection as predictor and gene expression as outcome.  Each gene was classified into one of the following trajectories based on models of time from HIV-1 infection and expression changes: 1) persistently up-regulated, 2) persistently down-regulated, 3) transiently up-regulated and 4) transiently down-regulated.  Genes with an adjusted p-value less than 0.05 and at least a 1.5-fold-change in expression after infection were classified into these trajectories.  A) Volcano plot showing maximum predicted log2 expression change versus –log10 adjusted p-value.  We determined the maximum change by estimating the change at each time point following HIV-1 infection using the linear model and finding the largest difference from pre-infection.  The 5 genes with the largest fold-change following HIV-1 infection from each trajectory are labelled. B) Predicted trajectories for 5 genes with lowest p-value from each trajectory. C) Heatmap comparing gene expression before HIV-1 infection versus during acute infection.  Rows represent 209 genes classified into the four expression trajectories.  Columns represent samples collected prior to HIV-1 infection and after HIV-1 infection when HIV-1 RNA was detected but not HIV-1 antibodies."}

source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/Figure1.R')
p.all


```


## Enrichment analysis reveals over-representation of IFN stimulated and immune response genes in the upregulated expression trajectories


```{r Figure2, collapse=TRUE, message=FALSE, fig.cap="Figure 2. Gene sets signifying inflammatory responses that are over-represented among post-HIV-1 infection expression trajectories.  A) Results from chi-squared and Fisher’s exact tests to evaluate whether genes in each Hallmark gene set were associated with expression trajectories.  Relative risks represent the relative probability that genes in a set were in a trajectory versus genes not in that set.  B-D) Heatmaps showing expression changes post-infection versus pre-infection for genes in significant gene sets (adj. p-value<0.05) for persistently up-regulated (B), transiently up-regulated (C) and persistently down-regulated genes (D)."}

source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/Figure2.R')

```

```{r FigureS4, collapse=TRUE, message=FALSE, fig.cap="Figure S4. Analysis of immune cell subpopulation-specific gene sets identifies genes involved in T cell and NK cell responses as being transiently up-regulated following HIV-1 infection.  A) Results from chi-squared and Fisher’s exact tests to evaluate whether genes in each gene set were associated with expression trajectories.  Relative risks represent the relative probability that genes in a set were in a trajectory versus genes not in that set.  B-C) Heatmaps showing expression changes post-infection versus pre-infection for genes in significant gene sets (adj. p-value<0.05) for transiently upregulated (B) and persistently downregulated (C) genes."}

source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/FigureS4.R')

```

```{r FigureS5, collapse=TRUE, message=FALSE, fig.cap="Figure S5. Interferon stimulated genes (ISGs) are enriched among genes with altered expression following HIV-1 infection. ISGs in this figure were captured in the Type I and II Interferome gene sets (http://www.interferome.org), which includes ~5,000 ISGs identified from experiments where cells or organisms were treated with an interferon.  A) Results from chi-squared and Fisher’s exact tests to evaluate whether genes in each gene set were associated with expression trajectories.  Relative risks represent the relative probability that genes in a set were in a trajectory versus genes not in that set.  B) Predicted gene expression trajectories for persistently up-regulated genes stimulated by Type I IFNs.  Predicted values at each days were based on linear mixed models for days after infection versus gene expression changes versus baseline.  C) Network analysis showing the transcription factors and their target genes identified among the ISGs. Transcription factor gene sets inferred from published ChIP-seq and other transcription factor binding site profiling studies and stored in the Harmonizome database (http://amp.pharm.mssm.edu/Harmonizome)"}

source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/FigureS5.R')

```

```{r NumIsgsByTrajectory}

source('./RScripts/Analysis_GseaFisher_Functions.R')
load('./DataIntermediate/pvs.Rdata')
load('./DataIntermediate/AllGeneSets.Rdata')
isgs <- c(all.sets$new.interferome[['IFN1_DWUP']], all.sets$new.interferome[['IFN2_DWUP']])
pvs$isg <- ifelse(pvs$Entrez_Gene_ID%in%isgs, 'ISG', 'Not ISG')
traj <- clean.data(data=pvs)
traj$any.change <- ifelse(traj$traj.fdr.fc=='No change', 'No change', 'Any change')

require(knitr)

kable(table(traj$any.change, traj$isg), caption='Number of genes with post-infection expression changes that are ISGs.')

kable(table(traj$traj.fdr.fc, traj$isg), caption='Number of genes with post-infection expression changes that are ISGs.')







```





## Cross-species confirmation of persistently upregulated ISGs during HIV-1 infection

```{r RmIsgPlot, collapse=TRUE, message=FALSE, fig.cap="Figure 3: Cross-species confirmation of persistently up-regulated ISGs. Shown are expression changes post HIV-1 infection of 20 ISGs in humans.  These 20 ISGs were previously found to be persistently up-regulated following SIV infection in rhesus macaques (Figure 5 in Bosinger et al., 2009).  A) ISG expression trajectories post HIV-1 infection.  B) Comparison of ISG expression in humans and rhesus macaques.  Ranks in humans are based on the maximum fold-change in expression after HIV-1 infection based on linear models.  Ranks in rhesus macaques are based on hierarchical clustering of expression values.  Correlation coefficient (R) from Spearman’s rank correlation test and associated p-value are shown."}

source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/Figure3_rhesusMacaques.R')
```

## Persistent up-regulation of pro-inflammatory cytokines and associations with ISG expression


```{r AnalyteResults}

load('./DataIntermediate/CytokineTimeSplinesPvs.Rdata')
cyt.pvs$best.fit <- NULL
DT::datatable(cyt.pvs, rownames=FALSE, caption='Post-infection cytokine trajectories')

```

## Shared relationships between persistently upregulated ISGs, plasma HIV-1 RNA copies and CXCL10 concentrations

```{r IsgAnalyteAssociationsTable, messages=FALSE, collapse=TRUE}

load('./DataIntermediate/IsgAssociationsWithAnalytesByTrajectory.Rdata')

require(knitr)
DT::datatable(analyte.isgs, caption='Number of ISGs associated with HIV-1 clinical outcomes and analyte concentrations, by post-infection trajectory.', rownames=FALSE)

```

```{r Figure4, message=FALSE, results='hide'}

### Code for create all parts of figure 4. Rmarkdown has trouble
### printing, I think because there is a tablegrob in a tablegrob and
### it breaks. Thus, we print each part separately below.
source('./RScripts/Analysis_GseaFisher_Functions.R')
source('./RScripts/Figure4.R')

```



```{r F4A, fig.cap="Figure 4. A) Longitudinal plasma cytokine trajectories.  Cytokines shown in color had adjusted p-values<0.05, except for CXCL10 which had an adjusted p-value=0.09.", collapse=T,message=FALSE}

cyt.plot

```

```{r F4B, message=FALSE, fig.cap="Figure 4. B) Associations of upregulated ISGs with cytokine serum concentrations, plasma HIV-1 RNA copies and blood CD4+ T cell counts.  Associations between each dataset pair were determined using linear mixed models with participant as random effect.  The threshold for a significant association was an adjusted p-value of ≤0.05. Fields for which the corresponding association had an adjusted p-value >0.05 are left white to indicate lack of association.  Associations of downregulated ISGs with cytokines and plasma HIV-1 are shown in the supplement."}


require(grid)
grid.draw(outcome.heatmap[[4]])


```

```{r F4C, fig.cap="Figure 4. C) Proportion of ISGs associated with plasma cytokine concentrations, plasma HIV-1 RNA copies and blood CD4+ T cell counts.", collapse=T,message=FALSE}

bar.p

```


```{r F4D, fig.cap="Figure 4. D) Scatterplot showing relationship between plasma CXCL10 concentrations and log10 HIV-1 RNA copies.", collapse=T,message=FALSE}

p3

```


```{r AnalyteOutcomesTable, message=FALSE, collapse=TRUE}

load('./DataIntermediate/AnalyteAssociationsWithOutcomes.Rdata')
analyte.outcomes <- lapply(names(analyte.outcomes), function(x){
    out <- data.frame(outcome=x,
                      analyte.outcomes[[x]])
    return(out)
})


DT::datatable(do.call(rbind, analyte.outcomes),
      caption="Analyte associations with HIV-1 outcomes.",
      rownames=FALSE)

```

# Session Information

```{r Session}

require(pander)
pander(sessionInfo(), compact = FALSE)


```

